package com.dc.bobaoge.project.v2.to.v3.business.core.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dc.bobaoge.base.entity.core.po.AuthenticationInfo;
import com.dc.bobaoge.base.entity.core.po.AuthenticationInfoHistory;
import com.dc.bobaoge.base.entity.core.po.AuthenticationInfoStore;
import com.dc.bobaoge.base.mapper.core.AuthenticationInfoHistoryMapper;
import com.dc.bobaoge.base.mapper.core.AuthenticationInfoMapper;
import com.dc.bobaoge.base.mapper.core.AuthenticationInfoStoreMapper;
import com.dc.bobaoge.common.constant.AuthenticationInfoTypeEnum;
import com.dc.bobaoge.common.em.PersonalCertificateEnum;
import com.dc.bobaoge.project.base.core.constant.BaseInfoConstant;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreCerCompany;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreCerMessage;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.component.common.util.list.ListUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * CerCompanySyncUtil
 *
 * @author chenxueli
 * @date 2024-01-29 10:06:00
 */
@Component
public class CerCompanySyncUtil {


    @Resource
    private AuthenticationInfoMapper authenticationInfoMapper;

    @Resource
    private AuthenticationInfoHistoryMapper authenticationInfoHistoryMapper;
    @Resource
    private AuthenticationInfoStoreMapper authenticationInfoStoreMapper;

    @Resource
    private CerCommonUtil cerCommonUtil;

    /**
     * 完善信息
     *
     * @param trigger           日志信息
     * @param oldCoreCerMessage 新的认证信息
     * @param company           新的认证人信息
     */
    public void runInfoPass(SyncTrigger trigger, OldCoreCerMessage oldCoreCerMessage, OldCoreCerCompany company) {
        // 查询是否已经存在信息了
        var history = authenticationInfoHistoryMapper.selectById(oldCoreCerMessage.getCerMsgId());
        if (history == null) {
            history = new AuthenticationInfoHistory();
            history.setAuditStatus(CerCommonUtil.STATUS_MAP.get(oldCoreCerMessage.getCerMsgState()));
            history.setId(oldCoreCerMessage.getCerMsgId());
            history.setVipType(oldCoreCerMessage.getCerType());
            history.setAdvertisementType(0);
            history.setFkUserId(oldCoreCerMessage.getCerUserId());
            history.setFkVipId(oldCoreCerMessage.getCerLevelId());
            history.setRfVipName(oldCoreCerMessage.getCerLevelName());
            history.setAuditRemark(oldCoreCerMessage.getCerMsgReason());
            history.setAuditTime(oldCoreCerMessage.getCerMsgVerfiy());
            history.setAvatar(company.getCerCompanyHeadimg());
            history.setAddress(company.getCerCompanyAddress());
            history.setDetailAddress(company.getCerCompanyAddress());
            history.setCertificateFront(company.getCerCompanyImg());
            history.setCertificateBack(company.getCerCompanyCon());
            history.setCertificateHand(company.getCerCompanyHand());
            history.setCertificateType(PersonalCertificateEnum.RECOGNIZE_ID_CARD.getType());
            history.setCertificateNo(company.getCerCompanyIdcard());
            history.setName(company.getCerCompanyName());
            history.setNickname(company.getCerCompanyNickname());
            history.setPhone(company.getCerCompanyPhone());
            history.setRfBusinessTypeName(cerCommonUtil.resolveBusinessTypeName(company.getCerCompanyRange()));
            history.setFkBusinessTypeId(cerCommonUtil.getBusinessTypeIdByName(history.getRfBusinessTypeName()));
            history.setOtherLicense(Stream.of(company.getCerCompanyOther(), company.getCerCompanyOther2()).filter(StringUtils::isNotBlank).collect(Collectors.joining(",")));
            history.setBankCardNo(company.getCerCompanyBankcard());
            history.setBusinessLicense(company.getCerCompanyMaster());
            history.setIsLegal(CerCommonUtil.CER_COMPANY_IDENTICAL_MAP.getOrDefault(company.getCerCompanyIdentical(), 0));
            history.setLegalCertificateFront(company.getCerCompanyAgentFace());
            history.setLegalCertificateBack(company.getCerCompanyAgentCon());
            history.setLegalCertificateHand(company.getCerCompanyAgentHand());
            history.setLegalCertificateNo(company.getCerCompanyAgentIdcard());
            history.setLegalName(company.getCerCompanyAgent());
            history.setLegalPhone(company.getCerCompanyAgentPhone());
            history.setLegalCertificateType(PersonalCertificateEnum.RECOGNIZE_ID_CARD.getType());
            authenticationInfoHistoryMapper.insert(history);
        } else {
            history.setAuditStatus(CerCommonUtil.STATUS_MAP.get(oldCoreCerMessage.getCerMsgState()));
            history.setId(oldCoreCerMessage.getCerMsgId());
            history.setVipType(oldCoreCerMessage.getCerType());
            history.setFkUserId(oldCoreCerMessage.getCerUserId());
            history.setFkVipId(oldCoreCerMessage.getCerLevelId());
            history.setRfVipName(oldCoreCerMessage.getCerLevelName());
            history.setAuditRemark(oldCoreCerMessage.getCerMsgReason());
            history.setAuditTime(oldCoreCerMessage.getCerMsgVerfiy());
            history.setAvatar(company.getCerCompanyHeadimg());
            history.setAddress(company.getCerCompanyAddress());
            history.setDetailAddress(company.getCerCompanyAddress());
            history.setCertificateFront(company.getCerCompanyImg());
            history.setCertificateBack(company.getCerCompanyCon());
            history.setCertificateHand(company.getCerCompanyHand());
            history.setCertificateType(PersonalCertificateEnum.RECOGNIZE_ID_CARD.getType());
            history.setCertificateNo(company.getCerCompanyIdcard());
            history.setName(company.getCerCompanyName());
            history.setNickname(company.getCerCompanyNickname());
            history.setPhone(company.getCerCompanyPhone());
            history.setOtherLicense(Stream.of(company.getCerCompanyOther(), company.getCerCompanyOther2()).filter(StringUtils::isNotBlank).collect(Collectors.joining(",")));
            history.setRfBusinessTypeName(cerCommonUtil.resolveBusinessTypeName(company.getCerCompanyRange()));
            history.setFkBusinessTypeId(cerCommonUtil.getBusinessTypeIdByName(history.getRfBusinessTypeName()));
            history.setBankCardNo(company.getCerCompanyBankcard());
            history.setBusinessLicense(company.getCerCompanyMaster());
            history.setIsLegal(CerCommonUtil.CER_COMPANY_IDENTICAL_MAP.getOrDefault(company.getCerCompanyIdentical(), 0));
            history.setLegalCertificateFront(company.getCerCompanyImg());
            history.setLegalCertificateBack(company.getCerCompanyAgentCon());
            history.setLegalCertificateHand(company.getCerCompanyAgentHand());
            history.setLegalCertificateNo(company.getCerCompanyAgentIdcard());
            history.setLegalName(company.getCerCompanyAgent());
            history.setLegalPhone(company.getCerCompanyAgentPhone());
            history.setLegalCertificateType(PersonalCertificateEnum.RECOGNIZE_ID_CARD.getType());
            authenticationInfoHistoryMapper.updateById(history);
        }
        // 查询押金信息
        var cerPayDeposit = cerCommonUtil.getOldCoreCerPayDepositByMsgId(oldCoreCerMessage.getCerUserId());
        // 查询对应的信息
        var authInfo = cerCommonUtil.getAuthInfoByUserId(oldCoreCerMessage.getCerUserId());
        if (authInfo == null) {
            authInfo = new AuthenticationInfo();
            authInfo.setFkUserId(history.getFkUserId());
            authInfo.setFkVipId(history.getFkVipId());
            authInfo.setRfVipName(history.getRfVipName());
            authInfo.setVipType(history.getVipType());
            authInfo.setAdvertisementType(history.getVipType());
            authInfo.setIsLegal(history.getIsLegal());
            authInfo.setAvatar(history.getAvatar());
            authInfo.setAddress(history.getAddress());
            authInfo.setDetailAddress(history.getDetailAddress());
            authInfo.setCertificateFront(history.getCertificateFront());
            authInfo.setCertificateBack(history.getCertificateBack());
            authInfo.setCertificateHand(history.getCertificateHand());
            authInfo.setCertificateType(history.getCertificateType());
            authInfo.setCertificateNo(history.getCertificateNo());
            authInfo.setName(history.getName());
            authInfo.setNickname(history.getNickname());
            authInfo.setPhone(history.getPhone());
            authInfo.setRfBusinessTypeName(cerCommonUtil.resolveBusinessTypeName(history.getRfBusinessTypeName()));
            authInfo.setFkBusinessTypeId(cerCommonUtil.getBusinessTypeIdByName(authInfo.getRfBusinessTypeName()));
            authInfo.setOtherLicense(history.getOtherLicense());
            authInfo.setBankCardNo(history.getBankCardNo());
            authInfo.setBusinessLicense(history.getBusinessLicense());
            authInfo.setLegalCertificateFront(history.getLegalCertificateFront());
            authInfo.setLegalCertificateBack(history.getLegalCertificateBack());
            authInfo.setLegalCertificateHand(history.getLegalCertificateHand());
            authInfo.setLegalCertificateNo(history.getLegalCertificateNo());
            authInfo.setLegalName(history.getLegalName());
            authInfo.setLegalPhone(history.getLegalPhone());
            authInfo.setLegalCertificateType(history.getLegalCertificateType());
            authInfo.setDays(0);
            authInfo.setFirstTime(history.getAuditTime());
            authInfo.setStartTime(history.getAuditTime());
            authInfo.setEndTime(history.getAuditTime().plusYears(1));
            authInfo.setTypeText(AuthenticationInfoTypeEnum.getShortNameByType(company.getCerCompanyTag()));
            if (cerPayDeposit != null) {
                authInfo.setDeposit((int) (cerPayDeposit.getCerPayTotal() * 100));
                authInfo.setDepositTradeNo(cerPayDeposit.getCerOrderNo());
            }
            authenticationInfoMapper.insert(authInfo);
        } else {
            authInfo.setFkUserId(history.getFkUserId());
            authInfo.setFkVipId(history.getFkVipId());
            authInfo.setRfVipName(history.getRfVipName());
            authInfo.setVipType(history.getVipType());
            authInfo.setAdvertisementType(history.getVipType());
            authInfo.setIsLegal(history.getIsLegal());
            authInfo.setAvatar(history.getAvatar());
            authInfo.setAddress(history.getAddress());
            authInfo.setDetailAddress(history.getDetailAddress());
            authInfo.setCertificateFront(history.getCertificateFront());
            authInfo.setCertificateBack(history.getCertificateBack());
            authInfo.setCertificateHand(history.getCertificateHand());
            authInfo.setCertificateType(history.getCertificateType());
            authInfo.setCertificateNo(history.getCertificateNo());
            authInfo.setName(history.getName());
            authInfo.setNickname(history.getNickname());
            authInfo.setPhone(history.getPhone());
            authInfo.setRfBusinessTypeName(cerCommonUtil.resolveBusinessTypeName(history.getRfBusinessTypeName()));
            authInfo.setFkBusinessTypeId(cerCommonUtil.getBusinessTypeIdByName(authInfo.getRfBusinessTypeName()));
            authInfo.setOtherLicense(history.getOtherLicense());
            authInfo.setBankCardNo(history.getBankCardNo());
            authInfo.setBusinessLicense(history.getBusinessLicense());
            authInfo.setLegalCertificateFront(history.getLegalCertificateFront());
            authInfo.setLegalCertificateBack(history.getLegalCertificateBack());
            authInfo.setLegalCertificateHand(history.getLegalCertificateHand());
            authInfo.setLegalCertificateNo(history.getLegalCertificateNo());
            authInfo.setLegalName(history.getLegalName());
            authInfo.setLegalPhone(history.getLegalPhone());
            authInfo.setTypeText(AuthenticationInfoTypeEnum.getShortNameByType(company.getCerCompanyTag()));
            authInfo.setLegalCertificateType(history.getLegalCertificateType());
            if (cerPayDeposit != null) {
                authInfo.setDeposit((int) (cerPayDeposit.getCerPayTotal() * 100));
                authInfo.setDepositTradeNo(cerPayDeposit.getCerOrderNo());
            }
            authenticationInfoMapper.updateById(authInfo);
        }
        // 更新店铺信息
        updateStore(
                company.getCerUserId(),
                company.getCerCompanyNickname(),
                company.getCerCompanyDetails(),
                company.getCerCompanyProduct(),
                company.getCerCompanyPremises()
        );
    }

    /**
     * 更新店铺信息
     *
     * @param userId      用户id
     * @param name        名称
     * @param detail      详情
     * @param productUrls 产品图片
     * @param sceneUrls   场景图片
     */
    private void updateStore(Long userId, String name, String detail, String productUrls, String sceneUrls) {
        // 查询id
        var wrapper = new LambdaQueryWrapper<AuthenticationInfoStore>()
                .eq(AuthenticationInfoStore::getFkUserId, userId);
        var store = authenticationInfoStoreMapper.selectOne(wrapper);
        if (store == null) {
            store = new AuthenticationInfoStore();
        }
        store.setName(name);
        store.setFkUserId(userId);
        store.setIntroduce(detail);
        if (StringUtils.isNotBlank(productUrls)) {
            store.setProductUrls(String.join(",", ListUtil.Spilt.to(productUrls, BaseInfoConstant.IMAGE_SPILT)));
        }
        // 场景图片
        store.setSceneUrls(
                ListUtil.Spilt.to(sceneUrls, (","))
                        .stream()
                        .filter(StringUtils::isNotBlank)
                        .flatMap(item -> ListUtil.Spilt.to(item, BaseInfoConstant.IMAGE_SPILT).stream())
                        .filter(StringUtils::isNotBlank)
                        .filter(item -> !"null".equals(item))
                        .distinct()
                        .collect(Collectors.joining(","))
        );
        // 保存店铺信息
        if (store.getId() == null) {
            authenticationInfoStoreMapper.insert(store);
        } else {
            authenticationInfoStoreMapper.updateById(store);
        }
    }

}
